<script setup lang="ts">
import { ref, computed, PropType, reactive, onMounted, watch } from 'vue'
import { ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElMessage } from 'element-plus'
import { TableData } from '@/api/account/types'
import { useValidator } from '@/hooks/web/useValidator'
import { getProjectOptionsListApi } from '@/api/account'
import { getProjectApi } from '@/api/dashboard/analysis'
import { useAppStore } from '@/store/modules/app'

const { required } = useValidator()
const appStore = useAppStore()
const isMobile = computed(() => appStore.getMobile)

// 数值验证器
const number = (message?: string) => {
  return {
    validator: (_, val, callback) => {
      if (!val) return callback()
      if (isNaN(Number(val)) || val === '') {
        callback(new Error(message || '请输入有效的数字'))
      } else {
        callback()
      }
    }
  }
}

const props = defineProps({
  currentRow: {
    type: Object as PropType<Nullable<TableData>>,
    default: () => null
  },
  selectedDay: {
    type: Number,
    default: null
  },
  currentDate: {
    type: Date,
    default: () => new Date()
  },
  selectedDayExpenditure: {
    type: Number,
    default: undefined
  },
  selectedDayScore: {
    type: Number,
    default: undefined
  }
})

// 计算当前日期标题 (已废弃，当前在Calendar组件中生成)
// const dialogTitle = computed(() => {  
//   const year = props.currentDate.getFullYear()
//   const month = props.currentDate.getMonth() + 1
//   const day = props.selectedDay
//   
//   return `${year}年${month}月${day}日`
// })
// 参与空投项目选项（包含 income 信息用于回显）
const projectOptions = ref<Array<{ label: string; value: string | number; income?: number }>>([])

// 获取所有项目列表（用于下拉框）
const getAllProjects = async () => {
  try {
    // 使用传入的日期信息，格式化为YYYY-MM-DD
    const year = props.currentDate.getFullYear()
    const month = String(props.currentDate.getMonth() + 1).padStart(2, '0')
    const day = String(props.selectedDay).padStart(2, '0')
    const currentDay = `${year}-${month}-${day}`
    
    const res = await getProjectApi({ day: currentDay })
    if (res && res.data) {
      // 处理返回数据，可能是数组或包含 items 的对象
      const items = Array.isArray(res.data) ? res.data : (res.data as any).items
      if (items && Array.isArray(items)) {
        // 将接口返回的项目转换为下拉选项格式
        projectOptions.value = items.map((item: any) => ({
          label: item.symbol || item.name,
          value: item.id,
          income: undefined // 初始没有收益值，会在 getProjectOptionsList 中更新
        }))
      }
    }
  } catch (error) {
    console.error('获取项目列表失败:', error)
  }
}
// 表单数据
interface IncItem {
  id?: number
  income?: number
}

const formData = reactive({
  id: props.currentRow?.id, // 从 AccountDialog.vue 传递的 currentRow.id
  scoreday: computed(() => {
    const year = props.currentDate.getFullYear()
    const month = String(props.currentDate.getMonth() + 1).padStart(2, '0')
    const day = String(props.selectedDay).padStart(2, '0')
    return `${year}-${month}-${day}`
  }),
  expenditure: props.selectedDayExpenditure !== undefined && props.selectedDayExpenditure !== null 
    ? String(props.selectedDayExpenditure) 
    : '0', // 不使用总耗损，不存在时显示0
  remarks: props.currentRow?.remarks,
  score: props.selectedDayScore !== undefined ? String(props.selectedDayScore) : '0',
  incs: [] as IncItem[] // 初始化为空数组，从接口加载后填充
})

// 监听 currentRow 变化，确保 formData.id 从 AccountDialog.vue 正确同步更新
watch(() => props.currentRow?.id, (newId) => {
  if (newId !== undefined) {
    formData.id = newId // 同步更新 formData.id
    // 耗损不更新（只使用 selectedDayExpenditure，不使用总耗损）
    if (!formData.remarks && props.currentRow?.remarks) {
      formData.remarks = props.currentRow.remarks
    }
  }
}, { immediate: true })

// 监听 selectedDayExpenditure 变化，更新耗损值
watch(() => props.selectedDayExpenditure, (newExpenditure) => {
  if (newExpenditure !== undefined && newExpenditure !== null) {
    formData.expenditure = String(newExpenditure)
  } else {
    formData.expenditure = '0' // 不存在时显示0
  }
}, { immediate: true })

// 监听日期变化，重新获取项目列表
watch([() => props.selectedDay, () => props.currentDate], () => {
  if (props.selectedDay !== null && props.selectedDay !== undefined) {
    getAllProjects()
    getProjectOptionsList()
  }
})


// 获取参与空投项目列表
const getProjectOptionsList = async () => {
  try {
    // 使用传入的日期信息，格式化为YYYY-MM-DD
    const year = props.currentDate.getFullYear()
    const month = String(props.currentDate.getMonth() + 1).padStart(2, '0')
    const day = String(props.selectedDay).padStart(2, '0')
    const currentDay = `${year}-${month}-${day}`
    
    // 确保使用 AccountDialog.vue 传递的 currentRow.id
    const accountId = props.currentRow?.id
    if (!accountId) {
      console.error('无法获取账户ID，请确保从 AccountDialog 正确传递 currentRow')
      return
    }
    
    const res = await getProjectOptionsListApi(
      {
        "id": accountId,
        "day": currentDay
      }
    )
    if (res && res.data && res.data.items) {
      // 更新已参与项目的 income 信息到 projectOptions
      res.data.items.forEach((item: any) => {
        const projectOption = projectOptions.value.find(option => option.value === item.id)
        if (projectOption) {
          projectOption.income = item.income !== undefined && item.income !== null ? Number(item.income) : undefined
        }
      })
      
      // 回显所有参与空投项目和收益值（如果有多个就回显多个）
      // 只要项目有 id，就回显出来，即使 income 为空也可以手动填写
      const itemsToDisplay = res.data.items.filter((item: any) => 
        item.id !== undefined && item.id !== null && item.id !== ''
      )
      
      if (itemsToDisplay.length > 0) {
        // 将接口返回的所有项目回显出来（包括有 income 和没有 income 的项目）
        formData.incs = itemsToDisplay.map((item: any) => ({
          id: Number(item.id),
          income: item.income !== undefined && item.income !== null && item.income !== '' ? Number(item.income) : undefined
        }))
      } else {
        // 如果接口返回的项目都没有有效的 id，至少保留一个空的项目行
        if (formData.incs.length === 0) {
          formData.incs = [{
            id: undefined,
            income: undefined
          }]
        }
      }
    } else {
      // 如果接口返回为空，至少保留一个空的项目行
      if (formData.incs.length === 0) {
        formData.incs = [{
          id: undefined,
          income: undefined
        }]
      }
    }
  } catch (error) {
    console.error('获取分组列表失败:', error)
  }
}
// 表单验证规则
const rules = reactive({
  score: [required(), number()],
  incs: [
    {
      validator: (_, val, callback) => {
        if (!val || !Array.isArray(val) || val.length === 0) {
          callback(new Error('至少需要添加一个收益项目'))
          return
        }
        
        // for (let i = 0; i < val.length; i++) {
        //   const item = val[i]
          // if (!item.income && item.income !== 0) {
          //   callback(new Error(`第${i + 1}行的收益不能为空`))
          //   return
          // }
          // if (isNaN(Number(item.income)) || item.income === '') {
          //   callback(new Error(`第${i + 1}行的收益请输入有效的数字`))
          //   return
          // }
        // }
        callback()
      }
    }
  ]
})

const formRef = ref<InstanceType<typeof ElForm>>()

// 添加收益项目
const addIncomeItem = () => {
  formData.incs.push({
    id: undefined,
    income: undefined
  })
}

// 删除收益项目
const removeIncomeItem = (index: number) => {
  if (formData.incs.length > 1) {
    formData.incs.splice(index, 1)
  }
}

// 当选择项目时，自动回显 income 值
const onProjectChange = (itemId: number | undefined, index: number) => {
  if (itemId !== undefined && itemId !== null) {
    // 从 projectOptions 中找到对应的项目
    const selectedProject = projectOptions.value.find(option => option.value === itemId)
    if (selectedProject && selectedProject.income !== undefined) {
      // 如果该收益项还没有设置 income 值，则自动填充
      if (formData.incs[index].income === undefined || formData.incs[index].income === null) {
        formData.incs[index].income = selectedProject.income
      }
    }
  }
}

const submit = async () => {
  if (!formRef.value) return false
  
  try {
    await formRef.value.validate()
    
    // PC端验证：income必须大于0
    if (!isMobile.value) {
      const hasInvalidIncome = formData.incs.some(item => {
        if (item.income !== undefined && item.income !== null) {
          const incomeValue = Number(item.income)
          return isNaN(incomeValue) || incomeValue <= 0
        }
        return false
      })
      
      if (hasInvalidIncome) {
        ElMessage.error('收益必须大于0!')
        return false
      }
    }
    
    // 过滤掉空项目并构建符合要求的参数结构
    // 只要有 income 就包含，id 必传（如果不存在则为 null）
    const filteredIncs = formData.incs
      .filter(item => item.income !== undefined && item.income !== null)
      .map(item => {
        return {
          id: (item.id !== undefined && item.id !== null) ? Number(item.id) : null,
          income: Number(item.income)
        }
      })
    
    // 确保提交时包含从 AccountDialog.vue 传递的 id
    return {
      ...formData,
      id: props.currentRow?.id, // 确保使用最新的 currentRow.id
      incs: filteredIncs
    }
  } catch (error) {
    console.log('表单验证失败:', error)
    return false
  }
}
// 组件挂载时获取分组数据
onMounted(async () => {
  // 先获取所有项目列表（用于下拉框）
  await getAllProjects()
  // 再获取已参与的项目列表（用于回显）
  await getProjectOptionsList()
})

defineExpose({
  submit
})
</script>

<template>
  <div class="update-revenue-container">
    <!-- 表单 -->
    <ElForm ref="formRef" :model="formData" :rules="rules" class="revenue-form">
      <!-- 第一排：总积分 -->
      <ElFormItem label="总积分" prop="score">
        <ElInput 
          v-model="formData.score" 
          placeholder="请输入总积分"
          style="width: 100%"
        />
      </ElFormItem>
      <!-- 第一排：耗损 -->
      <ElFormItem label="耗损" prop="expenditure">
        <span>{{ formData.expenditure || '0' }}</span>
      </ElFormItem>
      
      <!-- 第二排：参与项目 -->
      <ElFormItem label="参与空投" prop="incs">
        <div class="income-items-container">
          <div 
            v-for="(item, index) in formData.incs" 
            :key="index"
            class="income-item"
          >
            <ElSelect 
              v-model="item.id" 
              placeholder="选择项目"
              style="width: 45%; margin-right: 5%;"
              :clearable="!isMobile"
              @change="(value) => onProjectChange(value, index)"
            >
              <ElOption
                v-for="option in projectOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </ElSelect>
            <ElInput 
              v-model="item.income" 
              placeholder="输入收益"
              style="width: 45%; margin-right: 5%;"
            />
            <div class="item-actions">
              <el-button 
                v-if="index === 0" 
                type="primary" 
                size="small" 
                @click="addIncomeItem"
                class="add-btn"
              >
                +
              </el-button>
              <el-button 
                v-if="index > 0" 
                type="danger" 
                size="small" 
                @click="removeIncomeItem(index)"
                class="remove-btn"
              >
                -
              </el-button>
            </div>
          </div>
        </div>
      </ElFormItem>
      
      <!-- 第四排：今日余额 -->
      <!-- <ElFormItem label="今日余额" prop="todayBalance">
        <ElInput 
          v-model="formData.todayBalance" 
          placeholder="请输入今日余额"
          style="width: 100%"
        />
      </ElFormItem> -->
      
      <!-- 第五排：备注 -->
      <ElFormItem label="备注">
        <ElInput 
          v-model="formData.remarks" 
          type="textarea"
          :rows="3"
          placeholder="请输入备注信息"
          style="width: 100%"
        />
      </ElFormItem>
    </ElForm>
  </div>
</template>

<style scoped>
.update-revenue-container {
  padding: 16px 20px;
}

.form-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 20px;
  text-align: center;
  padding-bottom: 10px;
  border-bottom: 1px solid #e8e8e8;
}

.revenue-form {
  margin-top: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 18px;
  display: flex;
  align-items: flex-start;
}

:deep(.el-form-item__label) {
  width: 100px !important;
  text-align: right;
  font-size: 14px;
  font-weight: 500;
  color: #606266;
  line-height: 32px;
  padding-right: 12px;
  flex-shrink: 0;
}

:deep(.el-form-item__content) {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 8px;
}

:deep(.el-input__wrapper) {
  border-radius: 6px;
  min-height: 32px;
}

:deep(.el-select) {
  border-radius: 6px;
}

:deep(.el-select .el-input__wrapper) {
  min-height: 32px;
}

:deep(.el-textarea__inner) {
  border-radius: 6px;
  resize: vertical;
}

/* 收益项目容器样式 */
.income-items-container {
  width: 100%;
}

.income-item {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  gap: 8px;
}

.income-item:last-child {
  margin-bottom: 0;
}

.item-actions {
  display: flex;
  gap: 2px;
  min-width: 80px;
  margin-left: -17px;
}

.remove-btn {
  min-width: 16px;
  height: 16px;
  padding: 0;
  background-color: transparent;
  border: 1px solid #606266;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #606266;
}

.remove-btn:hover {
  background-color: #f5f7fa;
  border-color: #c0c4cc;
  color: #f56c6c;
}

.remove-btn:deep(.el-button__content) {
  font-size: 16px;
  font-weight: bold;
  line-height: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.add-btn {
  min-width: 16px;
  height: 16px;
  padding: 0;
  background-color: transparent;
  border: 1px solid #409eff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 0px;
  color: #409eff;
}

.add-btn:hover {
  background-color: #ecf5ff;
  border-color: #409eff;
  color: #409eff;
}

.add-btn:deep(.el-button__content) {
  font-size: 16px;
  font-weight: bold;
  line-height: 1;
}

/* 第三排特殊布局：参与项目和收入金额在同一行 */
:deep(.el-form-item:nth-child(3) .el-form-item__content) {
  display: block;
}

:deep(.el-form-item:nth-child(3) .el-select) {
  flex: none;
}

:deep(.el-form-item:nth-child(3) .el-input) {
  flex: none;
}
</style>
